package servlet;

import bean.Admin;
import bean.AdminRole;
import dao.AdminDao;
import dao.AdminRoleDao;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import util.JsonWrapper;
import util.ResponseUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * @author 邓晴予
 * 管理员权限管理
 */
public class AdminRoleServlet extends HttpServlet {
    private AdminRoleDao adminRoleDao = new AdminRoleDao();
    private AdminDao adminDao = new AdminDao();

    /**
     * @author 邓晴予
     * 管理员权限查询
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");

        String id = req.getParameter("id");
        String t = req.getParameter("t");
        JsonWrapper result = new JsonWrapper();
        List<Map<String, String>> resultAdminRole;  //查询返回的权限信息
        if ("admins".equals(t)) {
            // get all admin
            try {
                List<Object> al = adminDao.adminList2(null);
                if (al.size() > 0) {
                    JSONArray admins = new JSONArray();
                    try {
                        for (Object o : al) {
                            Admin admin = (Admin) o;
                            JSONObject adminJson = new JSONObject();
                            adminJson.put("adminId", admin.getAdminId());
                            adminJson.put("name", admin.getName());
                            adminJson.put("roleId", admin.getAdminRoleId());
                            AdminRole adminRole = new AdminRole();
                            adminRole.setAdminRoleId(admin.getAdminRoleId());
                            Map map = parseAdminRole(adminRoleDao.adminRoleList(null, adminRole));
                            map.remove("id");
                            JSONObject role = JSONObject.fromObject(map);
                            adminJson.put("auth", role);
                            admins.add(adminJson);
                        }
                        ResponseUtil.write(resp,
                            JsonWrapper.builder()
                                .setStatus(200)
                                .setMsg("success")
                                .setDataJsonArray("admins", admins).build());
                        return;
                    } catch (Exception e) {
                        ResponseUtil.write(resp,
                            JsonWrapper.builder()
                                .setStatus(301)
                                .setMsg("success")
                                .build());
                        return;
                    }
                } else {
                    ResponseUtil.write(resp,
                        JsonWrapper.builder()
                            .setStatus(200)
                            .setMsg("success")
                            .setDataJsonArray("admins", new JSONArray()).build());
                    return;
                }
            } catch (Exception e) {
                ResponseUtil.write(resp,
                    JsonWrapper.builder()
                        .setStatus(301)
                        .setMsg("success")
                        .build());
            }
        } else if (null != id) {
//			查询某个id管理员的权限
            AdminRole adminRole = new AdminRole();
            adminRole.setAdminRoleId(id);
            try {
                resultAdminRole = adminRoleDao.adminRoleList(null, adminRole);
                result.setStatus(200);
                result.setMsg("success");
                result.setDataJsonObject("privilege", JSONObject.fromObject(parseAdminRole(resultAdminRole)));
            } catch (Exception e) {
                result.setStatus(401);
                result.setMsg("failed");
            }
        } else {
//			查询所有权限
            try {
                resultAdminRole = adminRoleDao.adminRoleList(null, new AdminRole());
                result.setStatus(200);
                result.setMsg("success");
                JSONArray array = JSONArray.fromObject(parseAdminRoles(resultAdminRole));
                result.setDataJsonArray("values", array);
            } catch (Exception e) {
                result.setStatus(401);
                result.setMsg("failed");
            }
        }
        ResponseUtil.write(resp, result.get());
    }

    /**
     * @author 邓晴予
     * 修改给定id的管理员的权限
     */
    @Override
    protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");

        Admin admin = new Admin();
        admin.setAdminId(req.getParameter("uid"));
        admin.setAdminRoleId(req.getParameter("value"));
        JsonWrapper result = new JsonWrapper();

        try {
            if (adminDao.adminModify(admin)) {
                result.setStatus(200);
                result.setMsg("success");
            } else {
                result.setStatus(401);
                result.setMsg("failed");
            }
        } catch (Exception e) {
            result.setStatus(401);
            result.setMsg("failed");
        }
        ResponseUtil.write(resp, result);
    }

    private Collection<Map<?, ?>> parseAdminRoles(List<Map<String, String>> list) {
        Collection<Map<?, ?>> result = new ArrayList<>();
        for (Map<String, String> aList : list) {
            HashMap<String, Object> newMap = new HashMap<>(16);
            newMap.put("id", aList.get("adminroleid"));
            Map<String, Boolean> inMap = new HashMap<>(16);
            inMap.put("query", "1".equals(aList.get("requireadmin")));
            inMap.put("update", "1".equals(aList.get("updateadmin")));
            newMap.put("admin", inMap);

            inMap.put("query", "1".equals(aList.get("requireuser")));
            inMap.put("update", "1".equals(aList.get("updateuser")));
            newMap.put("user", inMap);

            inMap.put("query", "1".equals(aList.get("requireactivity")));
            inMap.put("update", "1".equals(aList.get("updateactivity")));
            newMap.put("activity", inMap);

            inMap.put("query", "1".equals(aList.get("requireadvice")));
            inMap.put("update", "1".equals(aList.get("updateadvice")));
            newMap.put("advice", inMap);

            inMap.put("query", "1".equals(aList.get("requirebicycle")));
            inMap.put("update", "1".equals(aList.get("updatebicycle")));
            newMap.put("bicycle", inMap);

            inMap.put("query", "1".equals(aList.get("requirecyclingrecord")));
            inMap.put("update", "1".equals(aList.get("updatecyclingrecord")));
            newMap.put("cyclingrecord", inMap);

            inMap.put("query", "1".equals(aList.get("requiredealrecord")));
            inMap.put("update", "1".equals(aList.get("updatedealrecord")));
            newMap.put("dealrecord", inMap);

            inMap.put("query", "1".equals(aList.get("requireconfig")));
            inMap.put("update", "1".equals(aList.get("updateconfig")));
            newMap.put("config", inMap);

            result.add(newMap);
        }
        return result;
    }

    private Map<String, Object> parseAdminRole(List<Map<String, String>> list) {
        HashMap<String, Object> newMap = new HashMap<>(16);
        Map<String, String> map = list.get(0);
        newMap.put("id", map.get("adminroleid"));
        Map<String, Boolean> inMap = new HashMap<>(16);
        inMap.put("query", "1".equals(map.get("requireadmin")));
        inMap.put("update", "1".equals(map.get("updateadmin")));
        newMap.put("admin", inMap);

        inMap.put("query", "1".equals(map.get("requireuser")));
        inMap.put("update", "1".equals(map.get("updateuser")));
        newMap.put("user", inMap);

        inMap.put("query", "1".equals(map.get("requireactivity")));
        inMap.put("update", "1".equals(map.get("updateactivity")));
        newMap.put("activity", inMap);

        inMap.put("query", "1".equals(map.get("requireadvice")));
        inMap.put("update", "1".equals(map.get("updateadvice")));
        newMap.put("advice", inMap);

        inMap.put("query", "1".equals(map.get("requirebicycle")));
        inMap.put("update", "1".equals(map.get("updatebicycle")));
        newMap.put("bicycle", inMap);

        inMap.put("query", "1".equals(map.get("requirecyclingrecord")));
        inMap.put("update", "1".equals(map.get("updatecyclingrecord")));
        newMap.put("cyclingrecord", inMap);

        inMap.put("query", "1".equals(map.get("requiredealrecord")));
        inMap.put("update", "1".equals(map.get("updatedealrecord")));
        newMap.put("dealrecord", inMap);

        inMap.put("query", "1".equals(map.get("requireconfig")));
        inMap.put("update", "1".equals(map.get("updateconfig")));
        newMap.put("config", inMap);
        return newMap;
    }
}
